package org.distributed.transaction.core.process;

import org.distributed.transaction.core.adapter.TransactionProcessorAdapter;
import org.distributed.transaction.core.connection.ProxyConnection;
import org.distributed.transaction.core.context.TransactionContext;
import org.distributed.transaction.core.context.TransactionStatus;
import org.distributed.transaction.core.exception.TransactionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class StartTransactionProcessor implements TransactionProcessor{

	@Autowired
	private TransactionProcessorAdapter transactionProcessorAdapter;

	@Override
	public void preBusinessCode(TransactionContext transactionContext) throws TransactionException {
		transactionProcessorAdapter.createGroup(transactionContext);
	}

	@Override
	public void onBusinessCodeError(TransactionContext transactionContext, Throwable throwable)
			throws TransactionException {
		transactionContext.setTransactionStatus(TransactionStatus.CANCELLING);
	}

	@Override
	public void onBusinessCodeSuccess(TransactionContext transactionContext, Object result)
			throws TransactionException {
		transactionContext.setTransactionStatus(TransactionStatus.CONFIRMING);
	}

	@Override
	public void clear(TransactionContext transactionContext) {
		transactionProcessorAdapter.notifyGroup(transactionContext);
		// 真的提交事务或者回滚事务
		ProxyConnection proxyConnection = (ProxyConnection) transactionContext
				.getConnection(transactionContext.getGroupId());
		proxyConnection.realExecute(transactionContext.getTransactionStatus());
	}

}
